package com.bestcem.xm.member.handler.imports.easyexcel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.exception.InvalidHeaderExcpetion;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.common.core.uitls.EnumUtil;
import com.bestcem.xm.common.core.uitls.JsonUtil;
import com.bestcem.xm.member.constant.ExcelFieldConstants;
import com.bestcem.xm.member.entity.mongo.ExtendFieldValue;
import com.bestcem.xm.member.entity.pojo.ExtendFieldEnumItemDO;
import com.bestcem.xm.member.entity.pojo.MemberDO;
import com.bestcem.xm.member.entity.pojo.ProjectDO;
import com.bestcem.xm.member.enums.ExtendFieldTypeEnum;
import com.bestcem.xm.member.enums.ImportRecordStatusEnum;
import com.bestcem.xm.member.enums.MemberTypeEnum;
import com.bestcem.xm.member.enums.NewMemberStatusEnum;
import com.bestcem.xm.member.service.ImportService;
import com.bestcem.xm.member.service.MemberService;
import com.bestcem.xm.member.service.ProjectService;
import com.bestcem.xm.member.service.dto.FieldDTO;
import com.bestcem.xm.member.service.param.ImportProjectParam;
import com.bestcem.xm.member.util.CheckUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

import static com.bestcem.xm.member.constant.Constants.M_PROJECT_BASE_EXCEL_HEADERS;
import static com.bestcem.xm.member.constant.Constants.PROJECT_FIELD_NAME_AND_FIELD_MAP;
import static com.bestcem.xm.member.handler.imports.ImportExcelUtil.*;

/**
 * 解析个人联系人数据
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/7/22
 */
@Slf4j
@Getter
@Setter
public class HttpReadProjectListener extends AnalysisEventListener<Map<Integer, String>> {

    private List<String> headers;

    private ImportProjectParam param;

    private MemberService memberService;

    private ImportService importService;

    private ProjectService projectService;

    private Integer per;

    private Integer count;

    private boolean isGetCount;

    private Boolean isStop;

    private JSONArray errorMsgJsons;

    /**
     * 机构名称对应的机构联系人
     */
    private String mid;


    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("执行失败", e);
        }

        // 设置进度条结束
        importService.deleteProgressBarStatus(0, param.getImportRecordId());

        JSONObject totalErrorMsg = new JSONObject();
        totalErrorMsg.put("-1", e.getMessage());

        JSONObject data = new JSONObject();
        data.put("receiveCount", 0);
        data.put("successCount", 0);
        data.put("failedCount", totalErrorMsg.size());
        data.put("total_error_msg", JsonUtil.jsonObjectToJsonArray(totalErrorMsg));
        importService.updateImportRecordData(param.getImportRecordId(), data, ImportRecordStatusEnum.IMPORT_RECORD_STATUS_FAILED.getIndex());
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        // 获取表头数据
        if (log.isInfoEnabled()) {
            log.info("开始获取表头数据");
        }
        headers = new ArrayList<>();
        headMap.forEach((k, v) -> {
            if (StrUtil.isNotEmpty(v)) {
                headers.add(v);
            }
        });
        if (log.isInfoEnabled()) {
            log.info("开始校验表头数据");
        }
        // 校验表头
        Set<String> headerSet = new HashSet<>(headers);
        if (headers.size() != headerSet.size()) {
            // 列名不唯一
            throw new InvalidHeaderExcpetion("列名不唯一");
        }
    }

    /**
     * 获取表头数据
     *
     * @param map
     * @param analysisContext
     */
//    @Override
//    public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {
//        // 获取表头数据
//        if (log.isInfoEnabled()) {
//            log.info("开始获取表头数据");
//        }
//        headers = new ArrayList<>();
//        map.forEach((k, v) -> {
//            if (StrUtil.isNotEmpty(v.getStringValue())) {
//                headers.add(v.getStringValue());
//            }
//        });
//        if (log.isInfoEnabled()) {
//            log.info("开始校验表头数据");
//        }
//        // 校验表头
//        Set<String> headerSet = new HashSet<>(headers);
//        if (headers.size() != headerSet.size()) {
//            // 列名不唯一
//            throw new InvalidHeaderExcpetion("列名不唯一");
//        }
//    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param analysisContext
     */
    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext analysisContext) {
        if (!isGetCount) {
            // 判断是否有表头数据，没有直接结束
            if (CollUtil.isEmpty(headers)) {
                throw new InvalidHeaderExcpetion("没有表头数据");
            }

            // 获取总行数
            Integer approximateTotalRowNumber =
                    analysisContext.readSheetHolder().getApproximateTotalRowNumber() - 1;
            count = approximateTotalRowNumber;
            if (approximateTotalRowNumber == 0) {
                // 没有数据
                isStop = true;
                return;
            }
            per = importService.getCalcUpdateProgressStep(count);
            // 初始化进度
            importService.setProgressBarStatus(0, param.getImportRecordId(), 0, count);
            isGetCount = true;
        }
        if (log.isInfoEnabled()) {
            log.info("解析到一条数据:{}", JSONObject.toJSONString(data));
        }
        // 获取当前解析的行数
        Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
        // fix 20211028 数据所在的行数
        Integer row = rowIndex + 1;
        handle(data, row);
        // 每per条更新一次进度
        if (rowIndex % per == 0) {
            // 每per条更新一次进度
            importService.setProgressBarStatus(0, param.getImportRecordId(), rowIndex, count);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 由于hasNext方法被重写,不一定能走到该方法
        if (!isStop) {
            finalOperation();
        }
    }

    /**
     * easyExcel 处理完所有数据之后,执行的后置操作
     *
     * @return void
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2021/8/31 15:42
     */
    private void finalOperation() {
        if (log.isInfoEnabled()) {
            log.info("所有数据解析完成");
        }
        //设置进度条结束
        importService.setProgressBarStatus(0, param.getImportRecordId(), count, count);
        int failedCount = errorMsgJsons.size();
        JSONObject dataJson = new JSONObject();
        dataJson.put("receiveCount", count);
        dataJson.put("successCount", count - failedCount);
        dataJson.put("failedCount", failedCount);
        dataJson.put("total_error_msg", errorMsgJsons);
        // 更新导入进度
        if (failedCount == count) {
            // 全部失败 设置记录为失败
            importService.updateImportRecordData(param.getImportRecordId(), dataJson, ImportRecordStatusEnum.IMPORT_RECORD_STATUS_FAILED.getIndex());
        } else {
            // 部分失败
            importService.updateImportRecordData(param.getImportRecordId(), dataJson, ImportRecordStatusEnum.IMPORT_RECORD_STATUS_SUCCESS.getIndex());
        }
    }

    private ServiceResult<String> handle(Map<Integer, String> data, Integer rowIndex) {
        JSONObject projectJson = buildMemberJson(data, headers, PROJECT_FIELD_NAME_AND_FIELD_MAP);

        String errorMessage = checkErrorMsg(projectJson, rowIndex);
        if (StrUtil.isNotEmpty(errorMessage)) {
            JSONObject errorMsgJson = new JSONObject();
            errorMsgJson.put(String.valueOf(rowIndex), errorMessage);
            errorMsgJsons.add(errorMsgJson);
            return ServiceResult.fail(errorMessage);
        }

        Map<String, ExtendFieldValue> fieldValList = new HashMap<>();
        Map<String, Boolean> updateFieldsIsNullMap = new HashMap<>();
        errorMessage = extendFieldCheck(projectJson, fieldValList, updateFieldsIsNullMap);
        if (StrUtil.isNotEmpty(errorMessage)) {
            JSONObject errorMsgJson = new JSONObject();
            errorMsgJson.put(String.valueOf(rowIndex), errorMessage);
            errorMsgJsons.add(errorMsgJson);
            return ServiceResult.fail(errorMessage);
        }
        ProjectDO project = buildProject(projectJson);
        save(project, fieldValList, updateFieldsIsNullMap);
        return ServiceResult.success();
    }

    private ProjectDO buildProject(JSONObject projectJson) {
        // 获取项目信息
        // ProjectDO project = projectService.findOneByOrgIdAndName(param.getOrgId(), projectJson.getString("m_project_name"));
        // 获取项目信息
        ProjectDO project = projectService.findOneByOrgIdAndMemberIdAndName(param.getOrgId(), mid, projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_NAME));
        String interiorMemberName = projectJson.getString("account_manager");
        String accountManager = "";
        // 获取 客户经理 id
        if (StrUtil.isNotEmpty(interiorMemberName)) {
            MemberDO member = memberService.findOneByNameAndMtypeAndStatusNe(interiorMemberName, MemberTypeEnum.INTERIOR.getIndex(),
                    NewMemberStatusEnum.MEMBER_STATUS_SOFT_DELETE.getIndex());
            if (ObjectUtil.isNotEmpty(member)) {
                accountManager = member.getId();
            }
        }
        String projectTimeStr = projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_TIME);
        String programStartStr = projectJson.getString(ExcelFieldConstants.PROJECT_PROGRAM_START);
        String actualStartStr = projectJson.getString(ExcelFieldConstants.PROJECT_ACTUAL_START);
        String acceptanceTimeStr = projectJson.getString(ExcelFieldConstants.PROJECT_ACCEPTANCE_TIME);
        if (!ObjectUtil.isEmpty(project)) {
            // 更新
            project.setOrgId(param.getOrgId());
            // project.setMemberId(dealUpdateFieldByObjectId(new ObjectId(mid), project.getMemberId(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setCode(dealUpdateFieldByString(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_CODE), project.getCode(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setName(dealUpdateFieldByString(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_NAME), project.getName(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setType(dealUpdateFieldByString(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_TYPE), project.getType(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setContractNo(dealUpdateFieldByString(projectJson.getString(ExcelFieldConstants.PROJECT_CONTRACT_NO), project.getContractNo(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setContractMoney(dealUpdateFieldByLong(projectJson.getLong(ExcelFieldConstants.PROJECT_CONTRACT_MONEY), project.getContractMoney(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setProjectTime(dealUpdateFieldByDate(projectTimeStr, project.getProjectTime(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setAccountManager(dealUpdateFieldByString(accountManager, project.getAccountManager(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setProjectManager(dealUpdateFieldByString(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_MANAGER), project.getProjectManager(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setProgramStartTime(dealUpdateFieldByDate(programStartStr, project.getProgramStartTime(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setActualStartTime(dealUpdateFieldByDate(actualStartStr, project.getActualStartTime(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setAcceptanceTime(dealUpdateFieldByDate(acceptanceTimeStr, project.getAcceptanceTime(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setStatus(dealUpdateFieldByString(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_STATUS), project.getStatus(), param.getExistedUpdate(), param.getNullUpdate()));
            project.setProjectManagerPhone(dealUpdateFieldByString(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_MANAGER_MOBILE), project.getProjectManagerPhone(), param.getExistedUpdate(), param.getNullUpdate()));

        } else {
            // 插入
            project = new ProjectDO();
            project.setOrgId(param.getOrgId());
            project.setMemberId(mid);
            project.setCode(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_CODE));
            project.setName(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_NAME));
            project.setType(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_TYPE));
            project.setContractNo(projectJson.getString(ExcelFieldConstants.PROJECT_CONTRACT_NO));
            project.setContractMoney(projectJson.getLong(ExcelFieldConstants.PROJECT_CONTRACT_MONEY));
            if (StrUtil.isNotBlank(projectTimeStr)) {
                project.setProjectTime(DateUtil.convertStringToDate(projectTimeStr, "yyyy/M/d"));
            } else {
                project.setProjectTime(null);
            }
            project.setAccountManager(accountManager);
            project.setProjectManager(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_MANAGER));
            if (StrUtil.isNotBlank(programStartStr)) {
                project.setProgramStartTime(DateUtil.convertStringToDate(programStartStr, "yyyy/M/d"));
            } else {
                project.setProgramStartTime(null);
            }
            if (StrUtil.isNotBlank(actualStartStr)) {
                project.setActualStartTime(DateUtil.convertStringToDate(actualStartStr, "yyyy/M/d"));
            } else {
                project.setActualStartTime(null);
            }
            if (StrUtil.isNotBlank(acceptanceTimeStr)) {
                project.setAcceptanceTime(DateUtil.convertStringToDate(acceptanceTimeStr, "yyyy/M/d"));
            } else {
                project.setAcceptanceTime(null);
            }
            project.setStatus(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_STATUS));
            project.setProjectManagerPhone(projectJson.getString(ExcelFieldConstants.PROJECT_PROJECT_MANAGER_MOBILE));
        }
        return project;
    }

    private String extendFieldCheck(JSONObject projectJson, Map<String, ExtendFieldValue> fieldValList, Map<String, Boolean> updateFieldsIsNullMap) {
        StringBuilder stringBuilder = new StringBuilder("");
        Collection<String> extendHeaders = CollUtil.subtract(headers, M_PROJECT_BASE_EXCEL_HEADERS);
        if (CollUtil.isNotEmpty(extendHeaders)) {
            extendHeaders.forEach(extendHeader -> {
                Map<String, FieldDTO> filedMap = param.getFiledMap();
                if (CollUtil.isNotEmpty(filedMap) && filedMap.containsKey(extendHeader)) {
                    // 获取该扩展字段对应的字段信息
                    FieldDTO fieldDTO = filedMap.get(extendHeader);
                    // 扩展字段id
                    String id = fieldDTO.getId();
                    // 扩展字段类型
                    Integer type = fieldDTO.getType();
                    // 获取excel中该字段的值
                    String value = projectJson.getString(extendHeader);

                    if (StrUtil.isEmpty(id)) {
                        return;
                    }
                    if (StrUtil.isNotEmpty(value) && ObjectUtil.isNotEmpty(type)) {
                        // 如果 存在值 且扩展字段类型也存在 对数据进行校验
                        switch (EnumUtil.getEnumByIndex(ExtendFieldTypeEnum.class, type)) {
                            case ENUM:
                                Map<String, List<ExtendFieldEnumItemDO>> extendFieldEnumMap =
                                        param.getExtendFieldEnumMap();
                                if (CollUtil.isNotEmpty(extendFieldEnumMap)) {
                                    List<ExtendFieldEnumItemDO> extendFieldEnumItems = extendFieldEnumMap.get(id);
                                    if (CollUtil.isEmpty(extendFieldEnumItems)) {
                                        // 该枚举不存在选项
                                        stringBuilder.append(StrUtil.format("扩展字段:{} 枚举项未在枚举字段值内", extendHeader));
                                        return;
                                    }
                                    List<String> names = extendFieldEnumItems.stream()
                                            .map(ExtendFieldEnumItemDO::getName).collect(Collectors.toList());
                                    if (CollUtil.isEmpty(names)) {
                                        stringBuilder.append(StrUtil.format("扩展字段:{} 枚举项未在枚举字段值内", extendHeader));
                                        return;
                                    }
                                    if (!names.contains(value)) {
                                        stringBuilder.append(StrUtil.format("扩展字段:{} 枚举项未在枚举字段值内", extendHeader));
                                        return;
                                    }
                                } else {
                                    stringBuilder.append(StrUtil.format("扩展字段:{} 枚举项未在枚举字段值内", extendHeader));
                                    return;
                                }
                                break;
                            case DATETIME:
                                // 检查日期 excel中日期是以yyyy/MM/dd 格式定义的的 但读取出来是 yyyy-MM-dd HH:mm:ss
                                ServiceResult<String> dateResult = CheckUtil.checkDateTimeFormat(value, "yyyy/M/d");
                                if (!dateResult.isSuccess() || !checkDateValue(value)) {
                                    stringBuilder.append(StrUtil.format("扩展字段:{} 格式错误", extendHeader));
                                    return;
                                }
                                // 修改 日期格式 yyyy/MM/dd
                                value = cn.hutool.core.date.DateUtil.parse(value, "yyyy/M/d")
                                        .toString("yyyy/MM/dd");
                                break;
                            case NUMBER:
                                // 检查数字
                                ServiceResult<String> numberResult = CheckUtil.checkNumberFormat(value);
                                if (!numberResult.isSuccess() || !checkNumValue(value)) {
                                    stringBuilder.append(StrUtil.format("扩展字段:{} 格式错误", extendHeader));
                                    return;
                                }
                                break;
                            case MOBILE:
                                // 检查手机号
                                ServiceResult<String> mobileResult = CheckUtil.checkMobilePhoneFormat(value);
                                if (!mobileResult.isSuccess()) {
                                    stringBuilder.append(StrUtil.format("扩展字段:{} 手机号码格式错误", extendHeader));
                                    return;
                                }
                                break;
                            case EMAIL:
                                // 检查邮箱
                                ServiceResult<String> result = CheckUtil.checkEmailFormat(value);
                                if (!result.isSuccess()) {
                                    stringBuilder.append(StrUtil.format("扩展字段:{} 邮箱格式错误", extendHeader));
                                    return;
                                }
                                break;
                            default:
                        }
                    }
                    ExtendFieldValue extendFieldValue = new ExtendFieldValue();
                    extendFieldValue.setFieldType(type);
                    extendFieldValue.setFieldValue(value);
                    extendFieldValue.setFieldName(extendHeader);
                    extendFieldValue.setFieldId(id);
                    fieldValList.put(id, extendFieldValue);
                    updateFieldsIsNullMap.put(id, StrUtil.isEmpty(value));
                }
            });
        }
        return stringBuilder.toString();
    }

    /**
     * 校验数据
     *
     * @param memberJson
     * @param rowIndex
     */
    private String checkErrorMsg(JSONObject memberJson, Integer rowIndex) {
        StringBuilder errMessage = new StringBuilder();
        String instituteName = memberJson.getString(ExcelFieldConstants.PROJECT_INSTITUTE_NAME);
        if (StrUtil.isEmpty(instituteName)) {
            errMessage.append("机构名称不能为空");
        } else if (instituteName.length() > 20) {
            errMessage.append("项目名称最长20个字");
        }

        // 机构名称查询不到对应的机构联系人
        List<MemberDO> members = memberService.findByOrgIdAndInstituteNameAndStatusNot(
                param.getOrgId(), instituteName, NewMemberStatusEnum.MEMBER_STATUS_SOFT_DELETE.getIndex());

        if (CollUtil.isEmpty(members)) {
            errMessage.append("机构名称查询不到对应的机构联系人");
        } else {
            mid = members.get(0).getId();
        }
        String mPType = memberJson.getString(ExcelFieldConstants.PROJECT_PROJECT_TYPE);
        if (StrUtil.isNotEmpty(mPType) && mPType.length() > 8) {
            errMessage.append("立项类型最长8个字");
        }

        String contractNo = memberJson.getString(ExcelFieldConstants.PROJECT_CONTRACT_NO);
        if (StrUtil.isNotEmpty(contractNo) && contractNo.length() > 20) {
            errMessage.append("合同编号最长20个字");
        }

        String projectManager = memberJson.getString(ExcelFieldConstants.PROJECT_PROJECT_MANAGER);
        if (StrUtil.isNotEmpty(projectManager) && projectManager.length() > 4) {
            errMessage.append("甲方项目经理最长4个字");
        }

        String mProjectName = memberJson.getString(ExcelFieldConstants.PROJECT_PROJECT_NAME);
        if (StrUtil.isEmpty(mProjectName)) {
            errMessage.append("项目名称为必填字段");
        }
        // 校验手机号
        String mobile = memberJson.getString(ExcelFieldConstants.PROJECT_PROJECT_MANAGER_MOBILE);
        if (StrUtil.isNotEmpty(mobile)) {
            ServiceResult<String> result = CheckUtil.checkMobilePhoneFormat(mobile);
            if (!result.isSuccess()) {
                errMessage.append("手机号格式错误");
            }
        }

        // 检查项目编号重复
        String mProjectCode = memberJson.getString(ExcelFieldConstants.PROJECT_PROJECT_CODE);
        if (StrUtil.isNotEmpty(mProjectCode)) {
            List<ProjectDO> projects = projectService.findByOrgIdAndMProjectCode(param.getOrgId(), mProjectCode);
            if (CollUtil.isNotEmpty(projects)) {
                for (ProjectDO project : projects) {
                    if (!mProjectName.equals(project.getName())) {
                        errMessage.append("项目编号重复");
                        break;
                    }
                }
            }
        }

        log.info(" 第 {} 行 {}", rowIndex, errMessage.toString());
        return errMessage.toString();
    }

    private void save(ProjectDO project, Map<String, ExtendFieldValue> fieldValList, Map<String, Boolean> updateFieldsIsNullMap) {
        if (StrUtil.isNotEmpty(project.getProjectId())) {
            // 获取该联系人 原有的扩展字段信息
            String fieldValListStr = project.getFieldValList();
            if (StrUtil.isNotEmpty(fieldValListStr)) {
                List<ExtendFieldValue> rawFieldValList = JSONArray.parseArray(fieldValListStr, ExtendFieldValue.class);
                if (CollUtil.isNotEmpty(rawFieldValList)) {
                    if (CollUtil.isNotEmpty(rawFieldValList)) {
                        rawFieldValList.forEach(field -> {
                            String fieldId = field.getFieldId();
                            if (fieldValList.containsKey(fieldId)) {
                                if (updateFieldsIsNullMap.getOrDefault(fieldId, false) && !param.getNullUpdate()) {
                                    fieldValList.put(fieldId, field);
                                } else if (!param.getExistedUpdate()) {
                                    fieldValList.put(fieldId, field);
                                }
                            } else {
                                fieldValList.put(fieldId, field);
                            }
                        });
                    }
                }
            }
            if (CollUtil.isNotEmpty(fieldValList)) {
                List<ExtendFieldValue> newFieldValList = new ArrayList<>();
                fieldValList.forEach((k, v) -> {
                    ExtendFieldValue extendFieldValue = buildExtendValue(v);
                    newFieldValList.add(v);
                });
                project.setFieldValList(JSONObject.toJSONString(newFieldValList));
            }
            // 更新时间
            project.setUpdateTime(DateUtil.getCommonDate());
            projectService.updateProject(project);
        } else {
            // 创建
            if (CollUtil.isNotEmpty(fieldValList)) {
                List<ExtendFieldValue> newFieldValList = new ArrayList<>();
                fieldValList.forEach((k, v) -> {
                    ExtendFieldValue extendFieldValue = buildExtendValue(v);
                    newFieldValList.add(v);
                });
                project.setFieldValList(JSONObject.toJSONString(newFieldValList));
            }
            // 创建时间
            project.setCreateTime(DateUtil.getCommonDate());
            // 更新时间
            project.setUpdateTime(project.getCreateTime());
            projectService.createProject(project);
        }
    }

    /**
     * 重写hasNext 为了实现有问题直接退出
     *
     * @param context
     * @return
     */
    @Override
    public boolean hasNext(AnalysisContext context) {
        if (isStop) {
            // 如果非抛出异常终止,则后续进行的操作
            finalOperation();
        }
        return !isStop;
    }
}
